package net.gazhi.delonix.core;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyObject;

import org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer;

/**
 * Class 工具类<br>
 * <br>
 * 
 * 使用了 jakarta-ustl 的部分代码<br>
 * 该项目已停止维护，Maven 上面也找不到
 * 
 * @author Jeffrey Lin
 *
 */
public final class ClassUtils {

	private ClassUtils() {
	}

	/**
	 * 获取 Hibernate 延迟加载实体的持久化类型<br>
	 * 如果不是延迟加载实体，就直接返回实体的类型
	 * 
	 * @param entity
	 * @return
	 */
	public static Class<?> getPersistentClassOfLazy(Object entity) {
		if (entity instanceof ProxyObject) {
			ProxyObject pxy = (ProxyObject) entity;
			MethodHandler hdl = pxy.getHandler();
			if (hdl instanceof JavassistLazyInitializer) {
				return ((JavassistLazyInitializer) hdl).getPersistentClass();
			}
		}
		return entity.getClass();
	}

	/**
	 * 根据类名加载类
	 * 
	 * @param className
	 * @return
	 * @throws ClassNotFoundException
	 */
	public static Class<?> loadClass(String className) throws ClassNotFoundException {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader == null) {
			classLoader = ClassUtils.class.getClassLoader();
		}
		return (classLoader.loadClass(className));
	}

	/**
	 * 获取类的常量
	 * 
	 * @param className
	 * @return
	 * @throws ClassNotFoundException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static Map<String, Object> getClassConstants(String className) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException {
		Map<String, Object> constants = new HashMap<String, Object>();
		Class<?> clazz = ClassUtils.loadClass(className);
		Field[] fields = clazz.getFields();
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			int modifiers = field.getModifiers();
			if ((modifiers & Modifier.STATIC) != 0 && (modifiers & Modifier.FINAL) != 0) {
				Object value = field.get(null);
				if (value != null) {
					constants.put(field.getName(), value);
				}
			}
		}
		return constants;
	}
}
